class Solution
{
public:
    typedef pair<string, int> PSI;
    struct Greater
    {
        bool operator()(const PSI &a, const PSI &b)
        {
            return a.second > b.second || (a.second == b.second && a.first < b.first);
        }
    };
    vector<string> topKFrequent(vector<string> &words, int k)
    {
        map<string, int> countMap;
        // 进行统计次数
        for (const auto &e : words)
            countMap[e]++;
        vector<PSI> tmp;
        for (const auto &e : countMap)
            tmp.push_back(e);
        sort(tmp.begin(), tmp.end(), Greater());
        vector<string> ans;
        for (int i = 0; i < k; ++i)
            ans.push_back(tmp[i].first);
        return ans;
    }
};